package cn.itcast.controller.cargo;


import cn.itcast.base.BaseController;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryProduct;
import cn.itcast.domain.cargo.FactoryProductExample;
import cn.itcast.service.cargo.FactoryProductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.utils.commons.DownloadUtil;
import cn.itcast.utils.commons.UtilFuns;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletContext;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping(value = "/baseinfo/factory")
@SuppressWarnings("all")
public class FactoryController extends BaseController {

    @Reference
    private FactoryService factoryService;

    @Reference
    private FactoryProductService factoryProductService;

    @RequestMapping(value = "/list",name = "全查分页")
    public String findAll(@RequestParam(defaultValue = "1") int pageNum,@RequestParam(defaultValue = "4") int pageSize){

        PageInfo page = factoryService.findByList(pageNum,pageSize);
        request.setAttribute("page",page);
        return "baseinfo/factory/factory-list";
    }

    @RequestMapping(value = "/toAdd",name = "到新增页面")
    public String toAdd(){
        //将厂家类型带到页面展示
        List<Factory> ctypeList = factoryService.findCtype();
        request.setAttribute("ctypeList",ctypeList);

        return "baseinfo/factory/factory-add";
    }

    @RequestMapping(value = "/edit",name = "厂家新增/编辑")
    public String edit(Factory factory){
        if (UtilFuns.isEmpty(factory.getId())){
            factoryService.save(factory);
        }else {
            factoryService.update(factory);
        }
        //展示最新数据
        return "redirect:/baseinfo/factory/list.do";
    }

    @RequestMapping(value = "/toView",name = "到查看页面")
    public String toView(String id){
        //根据id查
        Factory factory = factoryService.findById(id);
        request.setAttribute("factory",factory);
        return "baseinfo/factory/factory-view";
    }

    @RequestMapping(value = "/toUpdate",name = "到编辑页面")
    public String toUpdate(String id){
        //将厂家类型带到页面展示
        List<Factory> ctypeList = factoryService.findCtype();
        request.setAttribute("ctypeList",ctypeList);

        //根据id查，回显数据
        Factory factory = factoryService.findById(id);
        request.setAttribute("factory",factory);
        return "baseinfo/factory/factory-update";
    }

    @RequestMapping(value = "/delete")
    public String delete(String id){
        factoryService.delete(id);
        //展示最新数据
        return "redirect:/baseinfo/factory/list.do";
    }

    @RequestMapping(value = "/upload",name = "Excel表下载")
    public void upload(String id) throws IOException {//厂家id
        //根据厂家id查询货物
        FactoryProductExample factoryProductExample = new FactoryProductExample();
        FactoryProductExample.Criteria criteria = factoryProductExample.createCriteria();
        criteria.andFactoryIdEqualTo(id);
        List<FactoryProduct> list = factoryProductService.findAll(factoryProductExample);

        //通过厂家id获取厂家名称
        Factory factory = factoryService.findById(id);

        //将查询到的厂家下的产品放入Excel表中
        //创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建工作页
        XSSFSheet sheet = workbook.createSheet();
        //指定列宽
        sheet.setColumnWidth(1,11*256);
        sheet.setColumnWidth(2,19*256);
        sheet.setColumnWidth(3,11*256);
        sheet.setColumnWidth(4,14*256);
        sheet.setColumnWidth(5,13*256);
        sheet.setColumnWidth(6,13*256);
        sheet.setColumnWidth(7,13*256);
        //设定基本参数
        int rowIndex = 0;
        Row row = null;
        Cell cell = null;

        //设定第一行
        row = sheet.createRow(rowIndex++);
        //设置行高
        row.setHeightInPoints(36f);
        //创建单元格
        cell = row.createCell(1);
        //合并单元格  第0行到第0行  第1列到第7列
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,7));
        //设置单元格内容
        cell.setCellValue(factory.getFactoryName() + "厂家的产品信息表");
        //设置单元格样式
        cell.setCellStyle(bigTitle(workbook));

        //设定第二行
        row = sheet.createRow(rowIndex++);
        //设置行高
        row.setHeightInPoints(26f);
        //定义一个数组，保存表头数据
        String[] arr = {"","类型","生产厂家","数量","市场价","尺寸长","尺寸宽","尺寸高"};
        for (int i = 1;i < arr.length;i++){
            //创建单元格
            cell = row.createCell(i);
            //设置单元格值
            cell.setCellValue(arr[i]);
            //设置单元格样式
            cell.setCellStyle(title(workbook));
        }

        //设定剩下的所有行
        //遍历数据集合list
        for (FactoryProduct factoryProduct : list) {
            //创建行  有一个factoryProduct创建一行
            row = sheet.createRow(rowIndex++);
            //设置每一行的行高
            row.setHeightInPoints(24f);

            //设置每一行的第二个单元格
            cell = row.createCell(1);
            //设置单元格内容
            cell.setCellValue(factoryProduct.getCtype());
            //设置单元格样式
            cell.setCellStyle(text(workbook));

            //设置每一行的第三个单元格
            cell = row.createCell(2);
            //设置单元格内容
            cell.setCellValue(factoryProduct.getDescribeFactory());//生产厂家
            //设置单元格样式
            cell.setCellStyle(text(workbook));

            //设置每一行的第四个单元格
            cell = row.createCell(3);
            //设置单元格内容
            cell.setCellValue(factoryProduct.getpNumber());
            //设置单元格样式
            cell.setCellStyle(text(workbook));

            //设置每一行的第五个单元格
            cell = row.createCell(4);
            //设置单元格内容
            cell.setCellValue(factoryProduct.getPrice());
            //设置单元格样式
            cell.setCellStyle(text(workbook));

            //设置每一行的第六个单元格
            cell = row.createCell(5);
            //设置单元格内容
            cell.setCellValue(factoryProduct.getSizeLength());
            //设置单元格样式
            cell.setCellStyle(text(workbook));

            //设置每一行的第七个单元格
            cell = row.createCell(6);
            //设置单元格内容
            cell.setCellValue(factoryProduct.getSizeWidth());
            //设置单元格样式
            cell.setCellStyle(text(workbook));

            //设置每一行的第八个单元格
            cell = row.createCell(7);
            //设置单元格内容
            cell.setCellValue(factoryProduct.getSizeHeigth());
            //设置单元格样式
            cell.setCellStyle(text(workbook));
        }
        //提供下载功能  用工具类
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        new DownloadUtil().download(outputStream,response,"产品信息表.xlsx");

    }

    @RequestMapping(value = "/topdfUpload",name = "生成PDF")
    public void topdfUpload(String id) throws Exception {//厂家id
        //根据厂家id查询产品
        FactoryProductExample factoryProductExample = new FactoryProductExample();
        FactoryProductExample.Criteria criteria = factoryProductExample.createCriteria();
        criteria.andFactoryIdEqualTo(id);
        List<FactoryProduct> factoryProductList = factoryProductService.findAll(factoryProductExample);

        HashMap map = new HashMap();

        //加载pdf模板   factory.jasper
        ServletContext servletContext = session.getServletContext();
        String path = servletContext.getRealPath("/jasperPDF/factory4.jasper");
        FileInputStream inputStream = new FileInputStream(path);
        //动态填充数据
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(factoryProductList);
        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, map, dataSource);
        //导出PDF文件
        JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());

    }

    /*
        大标题样式
     */
    public CellStyle bigTitle(Workbook workbook){
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 16);
        font.setBold(true);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        return cellStyle;
    }

    /*
       小标题样式
    */
    public CellStyle title(Workbook workbook){
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        font.setBold(true);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER); //横向居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); //纵向居中
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        return cellStyle;
    }

    /*
        文字样式
     */
    public CellStyle text(Workbook workbook){
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.LEFT); //横向居左
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//纵向居中
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        return cellStyle;
    }
}
